package com.sunday.gateway.security.authentication;

import com.sunday.authorization.security.tools.userdetails.UserInfo;
import com.sunday.common.core.gson.GsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtException;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;

/**
 * @Description: jwt实体转化类
 * <p>
 * 此类中存在两个使用端点，分别是为了 权限判定 + 下游透传当前用户
 * com.sunday.gateway.security.authentication.CustomAuthenticatedReactiveAuthorizationManager
 * com.unicom.sms.web.gateway.filter.TokenTransferFilter
 */
@Slf4j
public class JwtAuthenticationConvert {

    public static UserInfo convert(JwtAuthenticationToken jwtAuthenticationToken) {
        Jwt jwt = jwtAuthenticationToken.getToken();
        return UserInfo.builder()
                .id(getClaim(jwt, "id"))
//                .username(getClaim(jwt, "user_name"))
                .permissionsSum(getPermissionsSum(jwtAuthenticationToken))
                .build();
    }

    public static long[] getPermissionsSum(JwtAuthenticationToken jwtAuthenticationToken) {
        Jwt jwt = jwtAuthenticationToken.getToken();
        if (!jwt.hasClaim("permission")) {
            throw new JwtException("Jwt解析用户数据异常");
        }
        try {
            return GsonUtils.DEFAULT.fromJson(jwt.getClaim("permission").toString(), long[].class);
        } catch (Throwable throwable) {
            log.error("jwt parse permissionsSum error : {}", throwable.toString());
            throw new JwtException("Jwt解析用户数据异常");
        }
    }

    public static <T> T getClaim(Jwt jwt, String claim) {
        if (!jwt.hasClaim(claim)) {
            throw new JwtException("Jwt解析用户数据异常");
        }
        return jwt.getClaim(claim);
    }

}
